package com.msk.web.controller.wlhy.goods;

import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Maps;
import com.msk.base.domain.goods.Goods;
import com.msk.base.domain.goodsMember.GoodsMember;
import com.msk.base.service.goods.GoodsService;
import com.msk.base.service.goodsMember.GoodsMemberService;
import com.msk.common.core.controller.BaseController;
import com.msk.common.core.domain.R;
import com.msk.common.core.domain.model.LoginUser;
import com.msk.common.core.page.TableDataInfo;
import com.msk.common.utils.StringUtils;
import com.msk.framework.web.utils.TokenUtils;
import com.msk.sys.domain.Dict;
import com.msk.sys.domain.Office;
import com.msk.sys.domain.User;
import com.msk.sys.service.OfficeService;
import com.msk.sys.utils.BaiduMapUtil;
import com.msk.sys.utils.DictMskUtils;
import com.msk.wlhy.domain.HtSupplier;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Api(tags = "货源接口")
@RestController
@RequestMapping("/api/goods")
public class BaseGoodsController extends BaseController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private GoodsMemberService goodsMemberService;
    /**
     * @Description 货主货源列表
     * @Author wlxiang
     * @Date 19:52 2023/6/5
     * @Param
     * @param params
     * @return com.msk.common.core.domain.R<?>
     **/
    @ApiOperation("货主货源列表")
    @PostMapping("/getGoodsList")
    public R<?> getGoodsList(@RequestBody Map<String,Object> params) {
        String contact = StringUtils.getString(params.get("contact"));
        params.put("orderByColumn","create_date");
        String isAsc = "DESC";
        if(StringUtils.isNotBlank(StringUtils.getString(params.get("isAsc")))&&"ASC".equals(StringUtils.getString(params.get("isAsc")))){
            isAsc = "ASC";
        }
        params.put("isAsc",isAsc);
        String publishWay = StringUtils.getString(params.get("publishWay"));
        String type = StringUtils.getString(params.get("type"));
        startPageJson(params,"");
        //货主审批状态查询
        List<Map<String,Object>> goodsList = goodsService.selectGoodsListByContact(contact,publishWay,type);
        TableDataInfo tableDataInfo = getDataTable(goodsList);
        List<Dict> typeDictList = DictMskUtils.getDictListNew("base_audit_type");
        List<Dict> goodsTypeDictList = DictMskUtils.getDictListNew("goods_type");
        for (Map<String,Object> goodsInfo : goodsList ) {
            publishWay = StringUtils.getString(goodsInfo.get("publishWay"));
            //发布类型
            String publishWayAlias = "";
            if(StringUtils.isNotBlank(publishWay)){
                if("1".equalsIgnoreCase(publishWay)){
                    publishWayAlias =  "直接发布";
                }else if("2".equalsIgnoreCase(publishWay)){
                    publishWayAlias =  "定向发布";
                }else if("3".equalsIgnoreCase(publishWay)){
                    publishWayAlias =  "竞价模式";
                }
            }
            goodsInfo.put("publishWayAlias",publishWayAlias);
            //转换后的货源类型
            String goodsTypeAlias = "";
            String goodsType = StringUtils.getString(goodsInfo.get("goodsType"));
            if(StringUtils.isNotBlank(goodsType)&&StringUtils.isNotEmpty(goodsTypeDictList)){
                goodsTypeAlias =  DictMskUtils.getDictLabelNew(goodsType, goodsTypeDictList, "");
            }
            goodsInfo.put("goodsTypeAlias",goodsTypeAlias);
            //
            type = StringUtils.getString(goodsInfo.get("type"));
            String typeAlias = null;
            if(StringUtils.isNotBlank(type)&&StringUtils.isNotEmpty(typeDictList)){
                typeAlias =   DictMskUtils.getDictLabelNew(type, typeDictList, "");
            }
            goodsInfo.put("typeAlias",typeAlias);
        }
        return R.appOk(tableDataInfo);
    }

    /**
     * @Description 货源详情
     * @Author wlxiang
     * @Date 14:30 2023/6/6
     * @Param
     * @param params
     * @return com.msk.common.core.domain.R<?>
     **/
    @ApiOperation("货源详情")
    @PostMapping("/getGoodsInfo")
    public R<?> getGoodsInfo(@RequestBody Map<String,Object> params) {
            String id = StringUtils.getString(params.get("id"));
        if(StringUtils.isBlank(id)){
            return R.appFail(400101,"请求参数货源ID#id为空");
        }
        return R.appOk(goodsService.get(id));
    }

    /**
     * @Description 新增货源
     * @Author wlxiang
     * @Date 15:36 2023/6/6
     * @Param
     * @param goods
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @ResponseBody
    @ApiOperation("新增货源")
    @RequestMapping(value = "saveGoods")
    public  R<?> saveGoods(@RequestBody Goods goods) {
        Map<String,Object> result = Maps.newHashMap();
        try {
            String  message = validateModel(goods);
            if (StringUtils.isNotBlank(message)){
                return R.appFail(400101,message);
            }
            //设置通用属性
            Office parent = new Office();
            parent.setId("0");
            Office office = new Office();
            office.setParent(parent);
            office.setType("");
            List<Office> officeList = officeService.findListOnly(office);
            if(officeList!=null && officeList.size()!=0){
                office = officeList.get(0);
                if(office!=null && office.getId()!=null){
                    goods.setCompany(office);
                    goods.setOffice(office);
                }else{
                    Office office1 = new Office();
                    office1.setId("1");
                    goods.setCompany(office1);
                    goods.setOffice(office1);
                }
            }

            String publishWay = goods.getPublishWay();
            if ( "3".equals(publishWay)){
                if(null==goods.getBlockPrice()){
                    goods.setBlockPrice(0.0);
                }
                if( StringUtils.isBlank(goods.getBlockPriceTotal())){
                    goods.setBlockPriceTotal("0.0");
                }
            }else {
                if(null==goods.getPrice()){
                    goods.setPrice(0.0);
                }
                if(null==goods.getAllPrice()){
                    goods.setAllPrice(0.0);
                }
            }
            String code = goods.getCode();
            if (StringUtils.isBlank(goods.getId()) || StringUtils.isBlank(code)) {
                code = goodsService.generateGoodsCode();
                goods.setCode(code);
            }
            LoginUser loginUser = TokenUtils.getMpLoginUser();
            GoodsMember goodsMember = goodsMemberService.getByLoginId(loginUser.getLoginId());
            goods.setCompany(goodsMember.getCompany());
            goods.setOffice(goodsMember.getOffice());
            goods.setContact(goodsMember.getCompany1().getId());
            goods.setContacts(goodsMember.getCompany1().getId());
            goods.setHtSupplier(new HtSupplier(goods.getHtSupplier().getSupplierId()));
            if(StringUtils.isBlank(goods.getContactUser())){
                goods.setContactUser(goods.getConsignerName());
            }

            if(StringUtils.isBlank(goods.getContact1User())){
                goods.setContact1User(goods.getConsigneeName());
            }
            if(!"0".equals( goods.getType()) && !"3".equals(goods.getPublishWay())){
                //C类货主需要上传支付凭证
                if("10".equals(goodsMember.getMemberLevel())){
                    if(StringUtils.isEmpty(goods.getTransferVoucher())){
                        return R.appFail(400101,"C类货主需要上传支付凭证");
                    }else{
                        goods.setPayWay("10"); //线下汇款
                        goods.setType("1"); //
                        goods.setPayTime(new Date());
                        goods.setPayStatus("1"); //已支付
                    }
                }
            }
            //设置货源起始位置坐标
            String startLocation = goods.getStartAreaName() + goods.getStartPlace();
            String endLocation = goods.getEndAreaName() + goods.getEndPlace();
            if(StringUtils.isNotEmpty(startLocation) && StringUtils.isNotEmpty(endLocation)){
                Map<String, Double> startLngAndLat = BaiduMapUtil.getLngAndLat(startLocation);
                goods.setStartCoordinate(startLngAndLat.get("lng") + "," + startLngAndLat.get("lat"));
                Map<String, Double> endLngAndLat = BaiduMapUtil.getLngAndLat(endLocation);
                goods.setEndCoordinate(endLngAndLat.get("lng") + "," + endLngAndLat.get("lat"));
            }
            goods.setCreateBy(new User(loginUser.getLoginId()));
            goodsService.saveNew(goods);
            result.put("flag", 1);
            if("0".equals( goods.getType())){
                result.put("message", "保存货源成功");
            }else{
                result.put("message", "货源发布成功");
            }
        } catch (Exception e) {
            logger.error("goods:{},e:{}",goods,e);
            return R.appFail(500101,"保存货源失败");
        }
        return R.appOk(result);
    }

    /**
     * @Description 线下上传支付凭证
     * @Author wlxiang
     * @Date 15:47 2023/6/9
     * @Param
     * @param params
     * @return com.msk.common.core.domain.R<?>
     **/
    @ResponseBody
    @RequestMapping(value = "offlinePayment")
    public R<?> offlinePayment(@RequestBody Map<String,Object> params) {
        Map<String,Object> result = Maps.newHashMap();
        try {

            String id = StringUtils.getString(params.get("id"));
            if(StringUtils.isBlank(id)){
                return R.appFail(400101,"请求参数货源ID#id为空");
            }
            String picPath =  StringUtils.getString(params.get("picPath"));
            if(StringUtils.isBlank(picPath)){
                return R.appFail(400101,"请求参数支付凭证#picPath为空");
            }
            if(!NumberUtil.isNumber(StringUtils.getString(params.get("payAmount")))){
                return R.appFail(400101,"请求参数支付金额#payAmount为空");
            }
            Double payAmount = Double.parseDouble(StringUtils.getString(params.get("payAmount")));
            Goods goods = new Goods(id);
            goods.setPayWay("10");
            goods.setType("1");
            goods.setPayTime(new Date());
            goods.setPayStatus("1");
            goods.setPayAmount(payAmount);
            goods.setTransferVoucher(picPath);
            goodsService.updatePayStatusById(goods);
            result.put("flag", 1);
            result.put("message", "上传支付凭证成功");
        } catch (Exception e) {
            logger.error("params:{},e:{}",params,e);
            return R.appFail(500101,"上传支付凭证失败");
        }
        return R.appOk(result);
    }

}
